package com.yanfan.ccapicode.controller;

import cn.hutool.core.util.StrUtil;
import com.yanfan.ccapicode.bean.dto.RequestTokenDTO;
import com.yanfan.ccapicode.bean.vo.AccessTokenVO;
import com.yanfan.ccapicode.service.OAuthService;
import com.yanfan.common.annotation.Anonymous;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * :)
 */
@Anonymous
@RestController
@RequestMapping("/oauth")
public class OAuthorizeController {

    @Autowired
    private OAuthService oAuthService;

    @RequestMapping("/authorize")
    public String authorize(@RequestParam("client_id") String clientId,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        return oAuthService.generateOAuthCode(clientId, request, response);
    }

    @RequestMapping("/access_token")
    public AccessTokenVO accessToken(@RequestParam(value = "code", required = false) String code,
                                     @RequestParam(value = "refresh_token", required = false) String refreshToken,
                                     @RequestParam("client_id") String clientId) {
        if (StrUtil.isNotBlank(refreshToken)) {
            //刷新令牌动作
            try {
                return oAuthService.generateAccessTokenByRefreshToken(refreshToken, clientId);
            } catch (Exception e) {
                //兼容谷歌
                return AccessTokenVO.builder().error("invalid_grant").build();
            }
        }
        /**
         * client_id: [xiaodu, xiaodu]
         * grant_type: [authorization_code, authorization_code]
         * client_secret: [xiaodumima, xiaodumima]
         * redirect_uri: [https://xiaodu-dbp.baidu.com/saiya/auth/4ffed8a2c646ffb3c1128a8aa962f483, https://xiaodu-dbp.baidu.com/saiya/auth/4ffed8a2c646ffb3c1128a8aa962f483]
         * dueros_uid: [41c55a2bca2d1e8e274703d3c976d1d3, 41c55a2bca2d1e8e274703d3c976d1d3]
         * open_id: [b1042f789e39405781ab30cad3cbcaeafd5acd8fb5621523c53d3c34ce2252b8, b1042f789e39405781ab30cad3cbcaeafd5acd8fb5621523c53d3c34ce2252b8]
         * code: [b99f64d4-0883-4df0-a870-a25a7938fbc5, b99f64d4-0883-4df0-a870-a25a7938fbc5]
         * */
        //兼容百度
        return oAuthService.generateAccessTokenByCode(code.split(",")[0], clientId.split(",")[0]);
    }


    /**
     * 客户端请求授权
     */
    @RequestMapping("/auth/api/{apiId}")
    public void requestExchangeAccessToken(@RequestBody RequestTokenDTO requestToken) {
        oAuthService.requestExchangeAccessToken(requestToken);
    }
}
